package cn.com.se.sharepictrue.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.com.se.sharepictrue.R;
import cn.com.se.sharepictrue.activity.PersonalHomepageActivity;
import cn.com.se.sharepictrue.activity.ShareDetailActivity;
import cn.com.se.sharepictrue.adapter.ShareListAdapter;
import cn.com.se.sharepictrue.application.Data;
import cn.com.se.sharepictrue.bean.HomeShareBean;
import cn.com.se.sharepictrue.business.CallBack;
import cn.com.se.sharepictrue.business.NetworkResponse;
import cn.com.se.sharepictrue.business.ShareApi;
import cn.com.se.sharepictrue.quickadapter.BaseAdapterHelper;
import cn.com.se.sharepictrue.utils.ToastUtils;
import cn.com.se.sharepictrue.widget.LoadMoreListener;

/**
 * Created by KIDNG on 2015/12/6.
 */
public class RankFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, ShareListAdapter.ShareItemStatusListener {
    private static final String BUNDLE_KEY_RANK = "BUNDLE_KEY_RANK";
    private static final int REQUEST_CODE_RANK = 1;
    @Bind(R.id.ll_rank_list)
    ListView mLlRankList;
    @Bind(R.id.srl_rank_refresh)
    SwipeRefreshLayout mSrlRankRefresh;
    private FragmentActivity mContext;
    private int mType;
    public static final int TYPE_ALL_PRAISE = 2;
    public static final int TYPE_TODAY_PRAISE = 0;
    public static final int TYPE_WEEK_PRAISE = 1;
    private List<HomeShareBean> mRankList;
    private ShareListAdapter mAdapter;

    private int nowPage = 1;
    private final int mLoadInLastRow = 4;
    private boolean hasMore;
    private LoadMoreListener mLoadMoreListener;

    public static RankFragment getNewInstance() {
        return getNewInstance(0);
    }

    public static RankFragment getNewInstance(int type) {
        RankFragment slf = new RankFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(BUNDLE_KEY_RANK, type);
        slf.setArguments(bundle);
        return slf;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_rank, container, false);
        ButterKnife.bind(this, view);
        Bundle args = getArguments();
        if (args != null)
            mType = args.getInt(BUNDLE_KEY_RANK);
        mContext = getActivity();
        initRefreshView();
        return view;
    }

    private void initRefreshView() {
        mSrlRankRefresh.setOnRefreshListener(this);
        mSrlRankRefresh.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
        mSrlRankRefresh.post(new Runnable() {
            @Override
            public void run() {
                mSrlRankRefresh.setRefreshing(true);
                initData();
            }
        });
    }
    private void initLoadMoreListener() {
        mLoadMoreListener = new LoadMoreListener(mLoadInLastRow) {
            @Override
            public void load() {
                nowPage++;
                ShareApi.getPraiseRank(mContext, mType, nowPage, new CallBack<NetworkResponse<List<HomeShareBean>>>() {
                    @Override
                    public void onFail() {
                        ToastUtils.show(mContext, "加载失败..");
                    }

                    @Override
                    public void onResponse(NetworkResponse<List<HomeShareBean>> response) {
                        if (!response.isStatus()) {//加载失败
                            ToastUtils.show(mContext, response.getError());
                        } else {
                            addToList(response.getData());
                            mLoadMoreListener.setLoading(false);
                        }
                        if (response.getHasMore() != null) {
                            if (response.getHasMore().equals(NetworkResponse.HAS_MORE)) {
                                hasMore = true;
                            } else {
                                hasMore = false;
                                mLoadMoreListener = null;
                            }
                        }
                    }
                });
            }
        };
    }

    private void addToList(List<HomeShareBean> data) {
        if (data != null) {
            mAdapter.addAll(data);
            mAdapter.notifyDataSetChanged();
        }
    }

    private void initData() {
        nowPage = 1;
        ShareApi.getPraiseRank(getActivity(), mType,nowPage, new CallBack<NetworkResponse<List<HomeShareBean>>>() {
            @Override
            public void onFail() {
                mSrlRankRefresh.setRefreshing(false);
                ToastUtils.show(getActivity(), "网络访问失败...orz");
            }

            @Override
            public void onResponse(NetworkResponse<List<HomeShareBean>> response) {
                mSrlRankRefresh.setRefreshing(false);
                if (!response.isStatus()) {//加载失败
                    ToastUtils.show(mContext, response.getError());
                } else {
                    mRankList = response.getData();
                    initList();
                }
            }
        });
    }

    private void initList() {
        if (mRankList != null && mRankList.size() > 0) {
            mAdapter = new ShareListAdapter(mContext, R.layout.item_share_list, mRankList);
            mAdapter.setShareItemStatusListener(this);
            mLlRankList.setAdapter(mAdapter);
            mLlRankList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(mContext, ShareDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("key", mAdapter.getItem(position));
                    intent.putExtra("item", bundle);
                    intent.putExtra("position", position);
                    startActivityForResult(intent, REQUEST_CODE_RANK);
                }
            });
            if (hasMore) {
                initLoadMoreListener();
                mLlRankList.setOnScrollListener(mLoadMoreListener);
            } else
                mLlRankList.setOnScrollListener(null);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onRefresh() {
        initData();
    }

    @Override
    public void avatarClick(BaseAdapterHelper helper, HomeShareBean item) {
        Intent intent = new Intent(mContext, PersonalHomepageActivity.class);
        Bundle bundle = new Bundle();
        //bundle.putSerializable(PersonalHomepageActivity.HOMEPAGE_SHAREINFO, item);
        bundle.putString(PersonalHomepageActivity.HOMEPAGE_USERID, item.getUserId());
        bundle.putString(PersonalHomepageActivity.HOMEPAGE_USERNAME, item.getUserName());
        bundle.putString(PersonalHomepageActivity.HOMEPGE_USERPIC, item.getAvatar());
        if (((Data) (mContext.getApplicationContext())).isLogin() && item.getUserId().contentEquals(((Data) (mContext.getApplicationContext())).getUserInfo().getUserID()))
            bundle.putString(PersonalHomepageActivity.HOMEPAGE_KEY, PersonalHomepageActivity.HOMEPAGE_ME);
        else
            bundle.putString(PersonalHomepageActivity.HOMEPAGE_KEY, PersonalHomepageActivity.HOMEPAGE_OTHER);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void concernClick(BaseAdapterHelper helper, final HomeShareBean item) {
        String concernId = item.getConcernUserId();
        if (concernId == null) ToastUtils.show(mContext, "请登录");
        else
            ShareApi.concern(mContext, item.getUserId(),
                    concernId.equals(HomeShareBean.HOME_SHARE_NO_CONCERN),
                    new CallBack<NetworkResponse<String>>() {
                        @Override
                        public void onFail() {
                            ToastUtils.show(mContext, "操作失败");
                        }

                        @Override
                        public void onResponse(NetworkResponse<String> response) {
                            if (!response.isStatus())
                                ToastUtils.show(mContext, response.getError());
                            else {
                                if (item.getConcernUserId().equals(HomeShareBean.HOME_SHARE_NO_CONCERN))
                                    item.setConcernUserId(item.getUserId());
                                else
                                    item.setConcernUserId(HomeShareBean.HOME_SHARE_NO_CONCERN);
                                mAdapter.notifyDataSetChanged();
                            }

                        }
                    });

    }

    @Override
    public void praiseClick(BaseAdapterHelper helper, final HomeShareBean item) {
        String likeIt = item.getPraiseStatus();
        if (likeIt == null) ToastUtils.show(mContext, "请登录");
        else if (likeIt.equals(HomeShareBean.HOME_SHARE_NO_PRAISE)) {
            ShareApi.praise(mContext, item.getShareId(), 1, new CallBack<NetworkResponse<String>>() {
                @Override
                public void onFail() {
                    ToastUtils.show(mContext, "点赞" + item.getUserName() + "失败");
                }

                @Override
                public void onResponse(NetworkResponse<String> response) {
                    if (!response.isStatus()) {
                        ToastUtils.show(mContext, response.getError());
                    } else {
                        item.setPraiseStatus(HomeShareBean.HOME_SHARE_IS_PRAISE);
                        item.setPraiseNum(item.getPraiseNum() + 1);
                        mAdapter.notifyDataSetChanged();
                    }
                }
            });
        } else if (likeIt.equals(HomeShareBean.HOME_SHARE_IS_PRAISE)) {
            ShareApi.praise(mContext, item.getShareId(), 0, new CallBack<NetworkResponse<String>>() {
                @Override
                public void onFail() {
                    ToastUtils.show(mContext, "点赞" + item.getUserName() + "失败");
                }

                @Override
                public void onResponse(NetworkResponse<String> response) {
                    if (!response.isStatus()) {
                        ToastUtils.show(mContext, response.getError());
                    } else {
                        item.setPraiseStatus(HomeShareBean.HOME_SHARE_NO_PRAISE);
                        item.setPraiseNum(item.getPraiseNum() - 1);
                        mAdapter.notifyDataSetChanged();
                    }
                }
            });
        }
    }

    @Override
    public void collectionClick(BaseAdapterHelper helper, final HomeShareBean item) {
        String favorite = item.getFavoriteStatus();
        if (favorite == null) ToastUtils.show(mContext, "请登录");
        else if (favorite.equals(HomeShareBean.HOME_SHARE_NO_FAVORITE)) {
            ShareApi.favorite(mContext, item.getShareId(), 1, new CallBack<NetworkResponse<String>>() {
                @Override
                public void onFail() {
                    ToastUtils.show(mContext, "收藏" + item.getUserName() + "失败");
                }

                @Override
                public void onResponse(NetworkResponse<String> response) {
                    if (!response.isStatus())
                        ToastUtils.show(mContext, response.getError());
                    else {
                        item.setFavoriteStatus(HomeShareBean.HOME_SHARE_IS_FAVORITE);
                        mAdapter.notifyDataSetChanged();
                    }

                }
            });
        } else {
            ShareApi.favorite(mContext, item.getShareId(), 0, new CallBack<NetworkResponse<String>>() {
                @Override
                public void onFail() {
                    ToastUtils.show(mContext, "取消收藏" + item.getUserName() + "失败");
                }

                @Override
                public void onResponse(NetworkResponse<String> response) {
                    if (!response.isStatus())
                        ToastUtils.show(mContext, response.getError());
                    else {
                        item.setFavoriteStatus(HomeShareBean.HOME_SHARE_NO_FAVORITE);
                        mAdapter.notifyDataSetChanged();
                    }
                }
            });
        }
    }

    @Override
    public void commentClick(BaseAdapterHelper helper, HomeShareBean item) {
        Intent intent = new Intent(mContext, ShareDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("key", item);
        intent.putExtra("item", bundle);
        intent.putExtra("position", helper.getPosition());
        startActivityForResult(intent, REQUEST_CODE_RANK);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        HomeShareBean item = null;
        int position = -1;
        if (requestCode == REQUEST_CODE_RANK && resultCode == Activity.RESULT_OK) {
            Log.d("xxxxxxxxxxxxxx", "return ok");
            if (data != null) {
                Bundle bundle = data.getBundleExtra("item");
                if (bundle != null)
                    item = (HomeShareBean) bundle.getSerializable("key");
                position = data.getIntExtra("position", -1);
            }
            if (item != null) Log.d("sssssss", item.toString());
            if (item != null && position != -1 && mAdapter.getCount() > position) {
                mAdapter.set(position, item);
            }
        }
    }
}
